using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Core;
using TMPro;

public class BattlePanel : BasePanel
{
    private TMP_InputField playerIdInput;
    private TextMeshProUGUI battleInfoTxt;

    protected override void OnInit(object data)
    {
        GetReference<ButtonEx>("startBtn").onClick = OnClickStart;
        GetReference<ButtonEx>("loadBtn").onClick = OnClickLoad;
        GetReference<ButtonEx>("saveBtn").onClick = OnClickSave;

        playerIdInput = GetReference<TMP_InputField>("playerIdInput");
        playerIdInput.text = UnityEngine.Random.Range(0, 1000).ToString();
        GetReference<ButtonEx>("connectBtn").onClick = OnClickConnect;

        battleInfoTxt = GetReference<TextMeshProUGUI>("battleInfoTxt");
    }

    private void OnClickConnect()
    {
        new SetPlayerId(int.Parse(playerIdInput.text)).Publish();
        new ConnectTcp("127.0.0.1", 8000).Publish();
    }

    private void OnClickStart()
    {
        new StartBattle().Publish();
    }

    private void OnClickLoad()
    {
        new LoadBattleRecord().Publish();
    }

    private void OnClickSave()
    {
        new SaveBattleRecord().Publish();
    }

    private StringBuilder builder = new StringBuilder();
    private void Update()
    {
        var info = new GetBattleInfo().Publish().battleInfo;
        if (info == null)
            return;

        builder.Clear();
        builder.AppendLine($"netDelayTime:{info.netDelayTime}");
        builder.AppendLine($"client:{info.clientFrameIndex}, server:{info.serverFrameIndex}");
        foreach (var item in info.playerInfos)
            builder.AppendLine($"id:{item.Key}, pos:{item.Value}");

        battleInfoTxt.text = builder.ToString();
    }
}
